package one.chapter_1.queue;

import java.util.Iterator;


public class LinkedQueue<Item> implements Queue<Item> {

    private class Node{
        Item item;
        Node next;
    }
    private Node head;
    private Node tail;
    private int size;
    public void enqueue(Item item) {

        Node oldTail=tail;
        tail=new Node();
        tail.item=item;
        if (oldTail==null){
            head=tail;
        }else {
            oldTail.next=tail;
        }

        size++;

    }

    public Item dequeue() {
        if (head==null){
            return null;
        }
        Node oldHead=head;
        head=oldHead.next;
        if (head==null){
           tail=null;
        }
        size--;
        return oldHead.item;
    }

    public boolean isEmpty() {
        return size!=0;
    }

    public int size() {
        return size;
    }

    public Iterator<Item> iterator() {
        return new Iter();
    }

    private class Iter implements Iterator<Item>{
        private Node nextNode=head;
        public boolean hasNext() {
            return nextNode!=null;
        }

        public Item next() {
            Item item=nextNode.item;
            nextNode=nextNode.next;
            return item;
        }

        public void remove() {

        }
    }

    public static void main(String[] args) {
        LinkedQueue<Integer> stack = new LinkedQueue<Integer>();

        stack.enqueue(6);
        stack.enqueue(5);
        stack.enqueue(4);
        stack.enqueue(3);
        stack.enqueue(2);
        stack.enqueue(1);
        Iterator<Integer> iterator = stack.iterator();
        while (iterator.hasNext()) {
            Integer val = iterator.next();
            System.out.println(val);
        }

        System.out.println(stack.dequeue());
        System.out.println(stack.dequeue());
        System.out.println(stack.dequeue());
        System.out.println(stack.dequeue());
        System.out.println(stack.dequeue());
        System.out.println(stack.dequeue());
        System.out.println(stack.dequeue());

    }
}
